package com.johnson.demos.file.Controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.johnson.demos.file.utils.AppendToFile;
import com.johnson.demos.file.vo.FileVo;

@RestController
@RequestMapping(value = "/api/file", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FileController
{

    @Value("${starting_point}")
    public String starting_point;
    
    //#base和jreap工程配置文件
    @Value("${base_datasources}")
    public String base_datasources;
    
    @Value("${base_dubbo}")
    public String base_dubbo;
    
    @Value("${base_resource}")
    public String base_resource;
    
    @Value("${jreap_datasources}")
    public String jreap_datasources;
    
    @Value("${jreap_dubbo}")
    public String jreap_dubbo;
    
    @Value("${jreap_resource}")
    public String jreap_resource;
    
    //#4a服务jar配置文件
    @Value("${base_application}")
    public String base_application;
    
    @Value("${base_jardubbo}")
    public String base_jardubbo;
    
    @Value("${jmanager_application}")
    public String jmanager_application;
    
    @Value("${jmanager_dubbo}")
    public String jmanager_dubbo;
    
    @Value("${bak_path}")
    public String bak_path;
    
    //移动端参数
    @Value("${mobapi_datasources}")
    public String mobapi_datasources;
    
    @Value("${mobapi_dubbo}")
    public String mobapi_dubbo;
    
    @Value("${mobapi_resource}")
    public String mobapi_resource;
    
    @Value("${mob_datasources}")
    public String mob_datasources;
    
    @Value("${mob_dubbo}")
    public String mob_dubbo;
    
    @Value("${mob_resource}")
    public String mob_resource;
    
    //日志组件
    @Value("${mq_application}")
    public String mq_application;
    
    static int flag = 1;//用来判断文件是否删除成功
    
    @GetMapping("/updatefile")
    @ResponseBody
    public String  updatefile(String ip,String nginxname,String sqluser,String sqlpwd,String jreapuser,String mobuser,String redispwd){
        FileVo filevo=new FileVo();
        filevo.setIp(ip);
        filevo.setJreapsqlusername(sqluser);
        filevo.setJreapsqlpwd(sqlpwd);
        filevo.setJreapuser(jreapuser);
        filevo.setMobsqluser(mobuser);
        filevo.setPort(nginxname);
        filevo.setRedispwd(redispwd);
        //删除文件夹下面所有文件在重新拷贝一份在更新配置
        //删除一个文件夹下的所有文件(包括子目录内的文件)
        File file = new File(starting_point);//输入要删除文件目录的绝对路径
        deleteFile(file);
        if (flag == 1){
            System.out.println("文件重置成功！");
        }
        
        dirCopy(bak_path, starting_point);
        
        //base和jreap公共配置
        String basefileName1 = starting_point+base_datasources;
        String basefileName2 = starting_point+base_dubbo;
        String basefileName3 = starting_point+base_resource;
        
        String jreapfileName1 = starting_point+jreap_datasources;
        String jreapfileName2 = starting_point+jreap_dubbo;
        String jreapileName3 = starting_point+jreap_resource;
        
        String datasources="\nresource.defaultDS.driverProperties.user ="+filevo.getJreapsqlusername()+"\nresource.defaultDS.driverProperties.password="+filevo.getJreapsqlpwd()+"\nresource.defaultDS.driverProperties.URL =jdbc:mysql://"+filevo.getIp()+"/"+filevo.getJreapuser()+"?useUnicode=true&characterEncoding=UTF-8&";
        String dubbostr="\ndubbo.registry.address=zookeeper://"+filevo.getIp()+":2181\ndubbo.metadata-report.address=zookeeper://"+filevo.getIp()+":2181";
        String redisstr="\nredis.cluster.nodes="+filevo.getIp()+":6379\nredis.password="+filevo.getRedispwd()+"\nipAddress=http://"+filevo.getIp()+":"+filevo.getPort()+"";
        //追加配置进jreap和base配置文件后
        AppendToFile.appendMethodA(basefileName1, datasources);
        AppendToFile.appendMethodA(basefileName2, dubbostr);
        AppendToFile.appendMethodA(basefileName3, redisstr);
        
        AppendToFile.appendMethodA(jreapfileName1, datasources);
        AppendToFile.appendMethodA(jreapfileName2, dubbostr);
        AppendToFile.appendMethodA(jreapileName3, redisstr);
        
        //base和jmanager的公共配置       
        String basejarfilename1=starting_point+base_application;
        String basejarfilename2=starting_point+base_jardubbo;
        
        String jmanagerfilename1 = starting_point+jmanager_application;
        String jmanagerfilename2 = starting_point+jmanager_dubbo;
        
        String applicationjar="\nspring.datasource.primary.url=jdbc:mysql://"+filevo.getIp()+":3306/"+filevo.getJreapuser()+"?useUnicode=true&characterEncoding=UTF-8&\nspring.datasource.primary.username="+filevo.getJreapsqlusername()+"\nspring.datasource.primary.password="+filevo.getJreapsqlpwd()+"\nredis.cluster.nodes="+filevo.getIp()+":6379\nredis.password="+filevo.getRedispwd()+"";
        //追加配置进base和jmanager配置文件后
        AppendToFile.appendMethodA(basejarfilename1, applicationjar);
        AppendToFile.appendMethodA(basejarfilename2, dubbostr);
        
        AppendToFile.appendMethodA(jmanagerfilename1, applicationjar);
        AppendToFile.appendMethodA(jmanagerfilename2, dubbostr);
        
        //移动服务端和后台配置.
        String mobdatasources="\nresource.defaultDS.driverProperties.user ="+filevo.getJreapsqlusername()+"\nresource.defaultDS.driverProperties.password="+filevo.getJreapsqlpwd()+"\nresource.defaultDS.driverProperties.URL =jdbc:mysql://"+filevo.getIp()+"/"+filevo.getMobsqluser()+"?useUnicode=true&characterEncoding=UTF-8&";
        String mobapi_mqandredis="\nredis.cluster.nodes="+filevo.getIp()+":6379\nredis.password="+filevo.getRedispwd()+"\nnamesvrAddr="+filevo.getIp()+":9876";
        String mob_redis="\nredis.cluster.nodes="+filevo.getIp()+":6379\nredis.password="+filevo.getRedispwd()+"";        
        
        String mobapifilename1=starting_point+mobapi_datasources;
        String mobapifilename2=starting_point+mobapi_dubbo;
        String mobapifilename3=starting_point+mobapi_resource;
        
        String mobfilename1=starting_point+mob_datasources;
        String mobfilename2=starting_point+mob_dubbo;
        String mobfilename3=starting_point+mob_resource;
        
        AppendToFile.appendMethodA(mobapifilename1, mobdatasources);
        AppendToFile.appendMethodA(mobapifilename2, dubbostr);
        AppendToFile.appendMethodA(mobapifilename3, mobapi_mqandredis);
        
        AppendToFile.appendMethodA(mobfilename1, mobdatasources);
        AppendToFile.appendMethodA(mobfilename2, dubbostr);
        AppendToFile.appendMethodA(mobfilename3, mob_redis);
        
        //日志组件
        String mqlogfilename=starting_point+mq_application;
        String mqstr="\nspring.datasource.url=jdbc:mysql://"+filevo.getIp()+":3306/"+filevo.getJreapuser()+"?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC\nspring.datasource.username="+filevo.getJreapsqlusername()+"\nspring.datasource.password="+filevo.getJreapsqlpwd()+"\nrocketmq.name-server="+filevo.getIp()+":9876";
        AppendToFile.appendMethodA(mqlogfilename, mqstr);
        return "GOOD!";
    }
    
    public static void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            flag = 0;
            System.out.println("文件重置失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = file.getName();
            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }
    
    
    public static void dirCopy(String srcPath, String destPath) {
        File src = new File(srcPath);
        if (!new File(destPath).exists()) {
            new File(destPath).mkdirs();
        }
        for (File s : src.listFiles()) {
            if (s.isFile()) {
                fileCopy(s.getPath(), destPath + File.separator + s.getName());
            } else {
                dirCopy(s.getPath(), destPath + File.separator + s.getName());
            }
        }
    }
    
    public static void fileCopy(String srcPath, String destPath) {
        File src = new File(srcPath);
        File dest = new File(destPath);
        //使用jdk1.7 try-with-resource 释放资源，并添加了缓存流
        try(InputStream is = new BufferedInputStream(new FileInputStream(src));
                OutputStream out =new BufferedOutputStream(new FileOutputStream(dest))) {
            byte[] flush = new byte[1024];
            int len = -1;
            while ((len = is.read(flush)) != -1) {
                out.write(flush, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
